// ============================== 导入依赖 ============================== //

import Vue from 'vue'

// ============================== 导出登录工具 ============================== //

export default {
  // —————————————————————————————— 更新结构树 —————————————————————————————— //

  updateTree(TREE, tree) {
    if (!tree || !tree.length) return

    const addIndex = []
    const delIndex = []

    // 查找待加序号
    tree.forEach((item, i) => {
      const has = TREE.some((ITEM) => ITEM.id === item.id)
      if (!TREE.length || !has) addIndex.push(i) // 正序，待加序号
    })

    // 查找待删序号
    TREE.forEach((ITEM, i) => {
      const index = tree.findIndex((item) => item.id === ITEM.id)
      if (index < 0) delIndex.unshift(i) // 倒序，待删除序号
      else {
        const { children, ...others } = tree[index]
        Object.assign(ITEM, others) // 更新节点
        this.updateTree(ITEM.children, children) // 递归调用
      }
    })

    // 删除不存在节点
    delIndex.forEach((index) => TREE.splice(index, 1))

    // 新增新来的节点
    addIndex.forEach((index) => {
      const { children, ...others } = tree[index]
      const ITEM = { children: [], ...others }
      TREE.push(ITEM) // 添加节点
      this.updateTree(ITEM.children, children) // 递归调用
    })
  },

  // —————————————————————————————— 更新多分支结构树 —————————————————————————————— //

  updateTreeMulti(TREE, tree) {
    const addIndex = []
    const delIndex = []

    // 查找待加序号
    tree.forEach((item, i) => {
      delete item.comReq // 无用属性
      delete item.comQuery // 无用属性
      const has = TREE.some((ITEM) => ITEM.id === item.id)
      if (!TREE.length || !has) addIndex.push(i) // 正序，待加序号
    })

    // 查找待删序号
    TREE.forEach((ITEM, i) => {
      const index = tree.findIndex((item) => item.id === ITEM.id)
      if (index < 0) delIndex.unshift(i) // 倒序，待删除序号
      else {
        const { children, ...others } = tree[index]
        Object.assign(ITEM, others) // 更新节点
        this.updateTreeMulti(ITEM.children, children) // 递归调用
      }
    })

    // 删除不存在节点
    delIndex.forEach((index) => TREE.splice(index, 1))

    // 新增新来的节点
    addIndex.forEach((index) => {
      const { children, ...others } = tree[index]
      const ITEM = { children: [], ...others }
      TREE.push(ITEM) // 添加节点
      this.updateTreeMulti(ITEM.children, children) // 递归调用
    })

    // 添加 children 子树
    TREE.forEach((ITEM) => {
      const { children, childrenLeaf } = ITEM
      if (childrenLeaf) Vue.set(ITEM, 'nodes', [...childrenLeaf, ...children])
      else if (children.length) Vue.set(ITEM, 'nodes', children)
      else Vue.set(ITEM, 'nodes', [{ id: `${ITEM.id}-empty` }])
    })
  },
}
